package com.mydomain.debtbook;

import java.text.DecimalFormat;

import com.mydomain.debtbook.ResolveActivity.debtNameListAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ExpandableListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class ViewDebtActivity extends Activity {

	private DebtAdapter debtAdapter;
	private Cursor groupCursor;
	private Cursor debtNameCursor;
	private String childName;
	private String mainName;
	private String deleteDebt;
	private DecimalFormat myformatShort;
	private DecimalFormat myformatLong;
	private SimpleCursorAdapter cursorAdapter;
	private String highlightName;
	
	
	private ExpandableListAdapter listAdapter;
	private ExpandableListView expandListView;
	private ListView debtNamesList;
	
	
	private static final int MY_DELETE_DIALOG = 0;

	private boolean isNameList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		debtAdapter = ((debtBookApplication) this.getApplication())
				.getDatabaseAdapter();
		isNameList = true;
		setContentView(R.layout.view_debt_page);
		expandListView = (ExpandableListView) findViewById(R.id.vdp_expandDebts);
		debtNamesList = (ListView)findViewById(R.id.vdp_listContacts);
		initExpandableNameList(mainName);
		myformatShort = new DecimalFormat("###,###.00");
		myformatLong = new DecimalFormat("###,###");
		showDebtNames();
		highlightName = "";
		
		

		
	}
	
	
	private void showDebtNames() {
		debtNameCursor = debtAdapter.getAllItemCursor(DebtAdapter.DB_TB_NAMES);
		if (debtNameCursor != null) {
			startManagingCursor(debtNameCursor);
		}

		cursorAdapter = new debtNameListAdapter(this,
				R.layout.contacts_row, debtNameCursor,
				new String[] { DebtAdapter._ITEM },
				new int[] {R.id.cr_name });

		debtNamesList.setAdapter(cursorAdapter);


		debtNamesList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mainName = debtNameCursor.getString(debtNameCursor
						.getColumnIndexOrThrow(DebtAdapter._ITEM));
				
				
				highlightName = mainName;
				if (isNameList) {
					initExpandableNameList(mainName);
				} else {
					initExpandableDateList(mainName);
				}
				
				cursorAdapter.notifyDataSetChanged();
	
			}
		});
	}
	
	public class debtNameListAdapter extends SimpleCursorAdapter {

		private LayoutInflater mInflater;
		private Context context;
		private TextView nameTv;
		private String[] myFrom;

		public debtNameListAdapter(Context context, int layout, Cursor cursor,
				String[] from, int[] to) {

			super(context, layout, cursor, from, to);
			mInflater = LayoutInflater.from(context);
			this.context = context;
			myFrom = from;
		}

		@Override
		public void bindView(View view, Context context, Cursor c) {
			int nameCol = c.getColumnIndexOrThrow(myFrom[0]);

			String name = c.getString(nameCol);

			TextView nameTv = (TextView) view.findViewById(R.id.cr_name);

			nameTv.setText(name);
			
			
			if (name.equals(highlightName)) {
				nameTv.setTextColor(Color.parseColor("#778899"));
			} else {
				nameTv.setTextColor(Color.WHITE);
			}

		}
	}

	
	
	private void initExpandableDateList(String groupName) {
		groupCursor = debtAdapter.getAllDateCursor(mainName);

		listAdapter = new MyExpandableDateListAdapter(groupCursor, this,
				R.layout.debt_group_row, R.layout.debt_child_row_date,
				new String[] { DebtAdapter._CREATE_DATE,
						DebtAdapter._DEBTAMOUNT }, new int[] { R.id.gr_name,
						R.id.gr_debtamount }, new String[] { DebtAdapter._ID,
						DebtAdapter._DEBTAMOUNT, DebtAdapter._CATEGORY,
						DebtAdapter._NAME }, new int[] { R.id.crd_rowId,
						R.id.crd_debtamount, R.id.crd_category, R.id.crd_name });

		expandListView.setAdapter(listAdapter);

		expandListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View v, int position, long id) {
						Log.v("ViewDebtActivity", "longClick");
						TextView t = (TextView) v.findViewById(R.id.crd_rowId);

						if (t != null) {

							deleteDebt = t.getText().toString();
							showDialog(MY_DELETE_DIALOG);

						}
						return true;
					}
				});

		expandListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				TextView t = (TextView) v.findViewById(R.id.crd_rowId);
				startEdit(t.getText().toString());
				return true;
			}
		});

	}

	private void initExpandableNameList(String groupName) {
		groupCursor = debtAdapter.getAllPersonCursor(mainName);

		listAdapter = new MyExpandableNameListAdapter(groupCursor, this,
				R.layout.debt_group_row, R.layout.debt_child_row, new String[] {
						DebtAdapter._NAME, DebtAdapter._DEBTAMOUNT },
				new int[] { R.id.gr_name, R.id.gr_debtamount }, new String[] {
						DebtAdapter._ID, DebtAdapter._DEBTAMOUNT,
						DebtAdapter._CATEGORY, DebtAdapter._CREATE_DATE },
				new int[] { R.id.cr_rowId, R.id.cr_debtamount,
						R.id.cr_category, R.id.cr_date });

		expandListView.setAdapter(listAdapter);


		expandListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View v, int position, long id) {
						Log.v("ViewDebtActivity", "longClick");
						TextView t = (TextView) v.findViewById(R.id.cr_rowId);

						if (t != null) {

							deleteDebt = t.getText().toString();
							showDialog(MY_DELETE_DIALOG);

						}
						return true;
					}
				});

		expandListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				TextView t = (TextView) v.findViewById(R.id.cr_rowId);
				startEdit(t.getText().toString());
				return true;
			}
		});

	}

	private void startEdit(String _id) {
		startActivity(new Intent(this, EditDebtActivity.class).putExtra(
				"DEBT_ID", _id));
	}

	public class MyExpandableDateListAdapter extends SimpleCursorTreeAdapter {

		public MyExpandableDateListAdapter(Cursor cursor, Context context,
				int groupLayout, int childLayout, String[] groupFrom,
				int[] groupTo, String[] childrenFrom, int[] childrenTo) {
			super(context, cursor, groupLayout, groupFrom, groupTo,
					childLayout, childrenFrom, childrenTo);
		}

		@Override
		// Bascially for this part, you just need to figure out how to return a
		// children cursor given a group cursor
		protected Cursor getChildrenCursor(Cursor groupCursor) {
			// Given the group, we return a cursor for all the children within
			// that group

			childName = groupCursor.getString(groupCursor
					.getColumnIndex(DebtAdapter._CREATE_DATE));

			Cursor childCursor = debtAdapter.getDebtForDateCursor(mainName,
					childName);

			return childCursor;

		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {

			View view = super.getGroupView(groupPosition, isExpanded,
					convertView, parent);
			TextView parentViewDebt = (TextView) view
					.findViewById(R.id.gr_debtamount);
			TextView parentViewDollar = (TextView) view
					.findViewById(R.id.gr_dollarsign);

			double debt = Double.parseDouble(parentViewDebt.getText()
					.toString());

			if (debt == 0) {
				parentViewDebt.setTextColor(Color.GRAY);
				parentViewDollar.setTextColor(Color.GRAY);
			} else if (debt > 0) {
				parentViewDebt.setTextColor(Color.GREEN);
				parentViewDollar.setTextColor(Color.GREEN);
			} else {
				parentViewDebt.setTextColor(Color.RED);
				parentViewDollar.setTextColor(Color.RED);
			}

			if (Math.abs(debt) > 999999) {

				parentViewDebt.setText(myformatLong.format(debt)
						.substring(0, 6) + "...");

			} else if (Math.abs(debt) > 9999) {
				parentViewDebt.setText(myformatLong.format(debt) + "N");

			}  else {
				parentViewDebt.setText(myformatShort.format(debt));
				
			}

			return view;

		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {

			View view = super.getChildView(groupPosition, childPosition,
					isLastChild, convertView, parent);

			TextView childViewDebt = (TextView) view
					.findViewById(R.id.crd_debtamount);
			TextView childViewDollar = (TextView) view
					.findViewById(R.id.crd_dollarsign);

			double debt = Double
					.parseDouble(childViewDebt.getText().toString());

			if (debt == 0) {
				childViewDebt.setTextColor(Color.GRAY);
				childViewDollar.setTextColor(Color.GRAY);

			} else if (debt > 0) {
				childViewDebt.setTextColor(Color.GREEN);
				childViewDollar.setTextColor(Color.GREEN);

			} else {
				childViewDebt.setTextColor(Color.RED);
				childViewDollar.setTextColor(Color.RED);

			}

			if (Math.abs(debt) > 999999) {

				childViewDebt.setText(myformatLong.format(debt).substring(0, 6)
						+ "...");

			} else if (Math.abs(debt) > 9999) {
				childViewDebt.setText(myformatLong.format(debt));

			}else {
				childViewDebt.setText(myformatShort.format(debt));
				
			}

			return view;

		}

	}

	public class MyExpandableNameListAdapter extends SimpleCursorTreeAdapter {

		public MyExpandableNameListAdapter(Cursor cursor, Context context,
				int groupLayout, int childLayout, String[] groupFrom,
				int[] groupTo, String[] childrenFrom, int[] childrenTo) {
			super(context, cursor, groupLayout, groupFrom, groupTo,
					childLayout, childrenFrom, childrenTo);
		}

		@Override
		// Bascially for this part, you just need to figure out how to return a
		// children cursor given a group cursor
		protected Cursor getChildrenCursor(Cursor groupCursor) {
			// Given the group, we return a cursor for all the children within
			// that group

			childName = groupCursor.getString(groupCursor
					.getColumnIndex(DebtAdapter._NAME));

			Cursor childCursor = debtAdapter.getDebtForPersonCursor(mainName,
					childName);
			return childCursor;

		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {

			View view = super.getGroupView(groupPosition, isExpanded,
					convertView, parent);
			TextView parentViewDebt = (TextView) view
					.findViewById(R.id.gr_debtamount);
			TextView parentViewDollar = (TextView) view
					.findViewById(R.id.gr_dollarsign);

			double debt = Double.parseDouble(parentViewDebt.getText()
					.toString());
			if (debt == 0) {
				parentViewDebt.setTextColor(Color.GRAY);
				parentViewDollar.setTextColor(Color.GRAY);
			} else if (debt > 0) {
				parentViewDebt.setTextColor(Color.GREEN);
				parentViewDollar.setTextColor(Color.GREEN);
			} else {
				parentViewDebt.setTextColor(Color.RED);
				parentViewDollar.setTextColor(Color.RED);
			}

			if (Math.abs(debt) > 999999) {

				parentViewDebt.setText(myformatLong.format(debt)
						.substring(0, 6) + "...");

			} else if (Math.abs(debt) > 9999) {
				parentViewDebt.setText(myformatLong.format(debt));

			} else {
				parentViewDebt.setText(myformatShort.format(debt));
			}

			return view;

		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {

			View view = super.getChildView(groupPosition, childPosition,
					isLastChild, convertView, parent);

			TextView childViewDebt = (TextView) view
					.findViewById(R.id.cr_debtamount);
			TextView childViewDollar = (TextView) view
					.findViewById(R.id.cr_dollarsign);

			double debt = Double
					.parseDouble(childViewDebt.getText().toString());

			if (debt == 0) {
				childViewDebt.setTextColor(Color.GRAY);
				childViewDollar.setTextColor(Color.GRAY);

			} else if (debt > 0) {
				childViewDebt.setTextColor(Color.GREEN);
				childViewDollar.setTextColor(Color.GREEN);

			} else {
				childViewDebt.setTextColor(Color.RED);
				childViewDollar.setTextColor(Color.RED);

			}

			if (debt > 999999) {

				childViewDebt.setText(myformatLong.format(debt).substring(0, 6)
						+ "...");

			} else if (debt > 9999) {
				childViewDebt.setText(myformatLong.format(debt));

			} else {
				childViewDebt.setText(myformatShort.format(debt));
			}

			return view;

		}

	}

	private void switchView() {
		if (isNameList) {

			initExpandableDateList(mainName);
			isNameList = !isNameList;
		} else {
			initExpandableNameList(mainName);
			isNameList = !isNameList;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (requestCode) {
		case 0:

			if (resultCode == RESULT_OK && intent.hasExtra("ItemId")) {

				mainName = intent.getStringExtra("ItemId");
				if (isNameList) {
					initExpandableNameList(mainName);
				} else {
					initExpandableDateList(mainName);
				}
			}
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_viewdebt, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mvd_new:
			startActivity(new Intent(this, NewDebtActivity.class));
			return true;
		case R.id.mvd_switch:
			switchView();
			return true;
		case R.id.mvd_setting:
			startActivityForResult(new Intent(this, ListNameActivity.class), 0);
			return true;
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case MY_DELETE_DIALOG:

			Cursor cursor = debtAdapter.getDebtByIdCursor(deleteDebt);
			cursor.moveToFirst();
			String lender = cursor.getString(cursor
					.getColumnIndex(DebtAdapter._LENDER));

			String debt = cursor.getString(cursor
					.getColumnIndex(DebtAdapter._DEBT));

			String borrower = cursor.getString(cursor
					.getColumnIndex(DebtAdapter._BORROWER));

			String category = cursor.getString(cursor
					.getColumnIndex(DebtAdapter._CATEGORY));

			String dateCreate = cursor.getString(cursor
					.getColumnIndex(DebtAdapter._CREATE_DATE));

			return new AlertDialog.Builder(this)
					.setTitle("Remove Debt")
					.setMessage(
							"Are you sure you want to remove the $"
									+ String.format("%.2f",
											Double.parseDouble(debt)) + " "
									+ lender + " owes " + borrower + " for "
									+ category + " on " + dateCreate)
					.setPositiveButton(getString(android.R.string.ok),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
									debtAdapter.removeDebt(deleteDebt);

									((SimpleCursorTreeAdapter) listAdapter)
											.getCursor().requery();

								}
							})
					.setNegativeButton(getString(android.R.string.cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
								}
							}).create();
		}

		return null;
	}

	@Override
	public void onResume() {
		super.onResume();
		
	}

}
